<template>
  <div class="container">
    <el-row :gutter="16">
      <el-col :span="6">
        <el-card shadow="never" style="padding:0;">
          <el-menu :default-active="active" @select="onSelect">
            <el-menu-item v-for="c in categories" :key="c.name" :index="c.name">
              {{ c.name }}<span class="muted">（{{ c.count }}）</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="never" style="margin-bottom: 12px;">
          <el-input v-model="keyword" placeholder="搜索关键词..." @keyup.enter="applyFilter" clearable style="max-width: 320px;" />
          <el-button type="primary" @click="applyFilter" style="margin-left:8px;">搜索</el-button>
        </el-card>

        <el-empty v-if="paged.length===0" description="暂无匹配文章" />
        <el-card v-for="p in paged" :key="p.id" shadow="hover" style="margin-bottom: 12px;" @click="$router.push(`/article/${p.id}`)">
          <h3 style="margin:0 0 8px;">{{ p.title }}</h3>
          <div class="muted">{{ p.date }} · {{ p.category }}</div>
          <p>{{ p.summary }}</p>
        </el-card>

        <div style="display:flex;justify-content:center;margin:16px 0;">
          <el-pagination layout="prev, pager, next" :page-size="pageSize" :total="filtered.length" :current-page="page" @current-change="onPageChange" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { fetchCategories, fetchPosts } from '@/services/blogService'

const route = useRoute()
const router = useRouter()
const categories = ref([])
const active = ref(route.query.category || '')
const keyword = ref(route.query.q || '')
const list = ref([])

onMounted(async () => {
  categories.value = await fetchCategories()
  await load()
})

async function load() {
  const { list: l } = await fetchPosts({ page: 1, pageSize: 1000, keyword: keyword.value, category: active.value })
  list.value = l
}

const page = ref(Number(route.query.page) || 1)
const pageSize = ref(6)
const filtered = computed(() => list.value)
const paged = computed(() => {
  const start = (page.value - 1) * pageSize.value
  return filtered.value.slice(start, start + pageSize.value)
})

function onSelect(name) {
  active.value = name
  syncToUrl()
}

function applyFilter() {
  syncToUrl()
}

function syncToUrl() {
  const q = {}
  if (active.value) q.category = active.value
  if (keyword.value) q.q = keyword.value
  if (page.value && page.value !== 1) q.page = String(page.value)
  router.replace({ query: q })
  load()
}

function onPageChange(p) { page.value = p; syncToUrl() }
</script>

<style scoped>
.muted { color: var(--color-muted); }
</style>


